/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.Map;
import java.util.Map.Entry;

import com.hiddenequity.tips.TipResponseParser;
import com.hiddenequity.tips.TipService;
import com.hiddenequity.utils.ApiErrorHumanizer;
import com.hiddenequity.utils.AppPreferences;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.Converter;
import com.hiddenequity.utils.UrlBuncher;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class Act_Super extends Activity{
	
	/*
	 * Activity result codes
	 */
	public static final int RESPONSE_REFRESH_REQUIRED = 15;
	public static final int RESPONSE_NO_REFRESH_REQUIRED = 16;
	public static final int RESPONSE_FINISH_REQUIRED = 17;
	public static final int RESPONSE_GOTO_MAIN_ACTIVITY = 18;

	
	/*
	 * Activity request codes
	 */
	public static final int REQUEST_REFRESH_REQUIRED = 4;
	public static final int REQUEST_NO_REFRESH_REQUIRED = 5;
	
	
	/*
	 * Async task codes
	 */
	public static final int OPERATION_GET_LIST = 6;
	public static final int OPERATION_SET_STATUS = 7;
	public static final int OPERATION_GET_DATA = 8;
	public static final int OPERATION_SET_DATA = 9;
	public static final int OPERATION_SET_PLATFORM = 10;
	public static final int OPERATION_SET_MOBILE = 11;
	public static final int OPERATION_PREPARE_DATA = 12;
	public static final int OPERATION_REMOVE_DATA = 13;
	public static final int OPERATION_GET_AUTH = 14;
	
	
	/*
	 * Statuses of AdWords items
	 */
	public static final int STATUS_ALL = 0;
	public static final int STATUS_ACTIVE = 1;
	public static final int STATUS_PAUSED = 2;
	public static final int STATUS_DELETED = 3;
	public static int statusSetTo;
	
	
	/*
	 * Filter current items
	 */
	public int dateRangeItem;
	public int statusItem;
	
	
	/*
	 * Titles of custom titlebar
	 */
    protected TextView title;
    protected TextView sub_title;
    protected LinearLayout filter;
    
    
    /*
     * Error string 
     */
    public static String responseErrorString;
    public static String formErrorString;
    

    /*
     * Totals
     */
    public static long totalClicks = 0;
    public static double totalCost = 0;
    public static long totalImpressions = 0;
    public static long totalConv = 0;
    public static double totalAvgCpc = 0;
    public static double totalCtr = 0;
    
    /*
     * Totals flags
     */
    public static final int SHOW_TOTALS_CLICKS_COST_CTR_CONV = 98;
    public static final int SHOW_TOTALS_CLICKS_COST_CTR_AVGCPC = 99;
    public static final int SHOW_TOTALS_CLICKS_COST_CTR_IMPR = 100;
    
    
    /*
     * Quote 
     */
    public static final char quote = (char) 34;
    
    
    /*
     * Thread for async task
     */
    public Thread thread = new Thread();
    
    
    
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
 
        setContentView(R.layout.main);
 
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
 
        title = (TextView) findViewById(R.id.title);
        sub_title = (TextView) findViewById(R.id.sub_title);
        filter = (LinearLayout) findViewById(R.id.ll_btnFilter);
    }//onCreate
	
    
    
    /*
     * Sum Totals
     */
    public static void uppendStatsToTotal(Map<String, String> item){
    	for (Entry<String, String> entry : item.entrySet()) {
	    	 String fieldName = entry.getKey();
	    	 String fieldValue = entry.getValue();
	    	 if(fieldName.equals("clicks")){
	    		 totalClicks = totalClicks + Long.parseLong(fieldValue);
	    	 } else if(fieldName.equals("cost")){
	    		 totalCost = totalCost + Double.parseDouble(fieldValue);
	    	 } else if(fieldName.equals("conv")){
	    		 totalConv = totalConv + Long.parseLong(fieldValue);
	    	 } else if(fieldName.equals("impressions")){
	    		 totalImpressions = totalImpressions + Long.parseLong(fieldValue);
	    	 }
	     }   	
    }//uppendStatsToTotal
    
    
    
    /*
     * Calculate total stats
     */
    public static void calculateTotalStats(){
    	if(totalClicks != 0){
	    	totalAvgCpc = totalCost/totalClicks;
	    	totalCtr = (totalClicks/totalImpressions) * 100;
    	}
    }//calculateTotalStats
    
    
    
    /*
     * Reset totals
     */
    public static void resetTotals(){
    	totalClicks = 0;
    	totalCost = 0;
    	totalCtr = 0;
    	totalConv = 0;
    	totalAvgCpc = 0;   
    	totalImpressions = 0;
    }//resetTotals
    
    
    
    /*
     * Check filter changes
     */
    public boolean isFilterChanged(int statusItem, int dateRangeItem){
    	boolean result = false;
    	
    	int currentStatus = AppPreferences.LoadPreferenceInt("status", 0, getApplication());
		int currentDateRange = AppPreferences.LoadPreferenceInt("dateRange", 0, getApplication());
		
		if(statusItem != currentStatus){
			statusItem = currentStatus;
			result = true;
		}
		
		if(dateRangeItem != currentDateRange){
			dateRangeItem = currentDateRange;
			result = true;
		}
		
		return result;
    }//isFilterChanged
    
    
    
    /*
     * Show totals
     */
    public void showStatsTotal(final int totalsToShow){
		//Set total clicks
    	TextView lbl_total_cell_1 = (TextView) findViewById(R.id.lbl_total_cell_1);
    	lbl_total_cell_1.setText(R.string.lbl_Clicks);
    	
    	TextView total_cell_1 = (TextView) findViewById(R.id.total_cell_1);
		total_cell_1.setText(Long.toString(totalClicks));
		
		
		//Set total Cost
    	TextView lbl_total_cell_2 = (TextView) findViewById(R.id.lbl_total_cell_2);
    	lbl_total_cell_2.setText(R.string.lbl_Cost);

		TextView total_cell_2 = (TextView) findViewById(R.id.total_cell_2);
		total_cell_2.setText(Converter.formatDouble(totalCost));
		
		
		//Set total Ctr
    	TextView lbl_total_cell_3 = (TextView) findViewById(R.id.lbl_total_cell_3);
    	lbl_total_cell_3.setText(R.string.lbl_Ctr);

		TextView total_cell_3 = (TextView) findViewById(R.id.total_cell_3);
		total_cell_3.setText(Converter.formatDouble(totalCtr));
		
		
		//Set total Conv Or AvgCpc
		TextView lbl_total_cell_4 = (TextView) findViewById(R.id.lbl_total_cell_4);
		TextView total_cell_4 = (TextView) findViewById(R.id.total_cell_4);
		
		switch (totalsToShow) {
			case SHOW_TOTALS_CLICKS_COST_CTR_CONV:
				lbl_total_cell_4.setText(R.string.lbl_Conv);
				total_cell_4.setText(Long.toString(totalConv));			
			break;
		
			case SHOW_TOTALS_CLICKS_COST_CTR_AVGCPC:
				lbl_total_cell_4.setText(R.string.lbl_AvCpc);
				total_cell_4.setText(Converter.formatDouble(totalAvgCpc));			
			break;
			
			case SHOW_TOTALS_CLICKS_COST_CTR_IMPR:
				lbl_total_cell_4.setText(R.string.lbl_Impr);
				total_cell_4.setText(Long.toString(totalImpressions));			
			break;
		}
    }//showStatsTotal
    
    
    
    /*
     * Filter toggler
     */
    public void filterToggler(int state){
		
    	final Button btn_toggleFilter = (Button) findViewById(R.id.btn_toggleFilter);
		final Drawable img_filter_off = getResources().getDrawable( R.drawable.ico_toggle_off );
		final Drawable img_filter_on = getResources().getDrawable( R.drawable.ico_toggle_on );

		LinearLayout filter = (LinearLayout) findViewById(R.id.ll_filter);
		if(state == View.GONE){
			filter.setVisibility(View.VISIBLE);
			btn_toggleFilter.setCompoundDrawablesWithIntrinsicBounds(img_filter_on, null, null, null);
			AppPreferences.SavePreferenceInt("filterToggle", View.GONE, getApplication());
		} else {
			filter.setVisibility(View.GONE);
			btn_toggleFilter.setCompoundDrawablesWithIntrinsicBounds(img_filter_off, null, null, null);
			AppPreferences.SavePreferenceInt("filterToggle", View.VISIBLE, getApplication());
		}

    }//filterToggler
    
    
    
    /*
     * Spinner inflater
     */
    public void inflateSpinner(Spinner spinner, int array, int selection){
    	Resources res = getResources();
    	
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item,
				res.getStringArray(array));
		
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		spinner.setAdapter(adapter);
	
		spinner.setSelection(selection);

    }//inflateSpinner

     
    
	/*
	 * Response error message
	 */
	public void showOperationError(int title, String error){
    	if(error != null){
        	
    		String strTitle = getString(title);
    		
    		if(error.contains(ApiErrorHumanizer.NOT_ADS_USER))
    			strTitle = AuthService.accountEmail;
    		
    		int  strResource = ApiErrorHumanizer.humanizeError(error);
    		if( strResource > 0){
    			error = getString(strResource);
    		}

			new AlertDialog.Builder(this)
					.setTitle(strTitle)		
					.setMessage(error)
					.setPositiveButton(R.string.btn_Ok, null)
					.setCancelable(false)
		    		.create()
		    		.show();
			
        	return;
    	}		
	}//isErrorOnResponse

	
	
	/*
	 * Connection checker
	 */
	public boolean isConnectionAvalable(){
		boolean result = true;
		
		//Check Internet availability
        if(Communication.isOnline((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))) {
            if(! Communication.isSourceAvalable(UrlBuncher.URL_TEST)){

            	new AlertDialog.Builder(this)
    					.setTitle(R.string.msg_title_no_connection)
						.setMessage(R.string.msg_no_source)
						.setPositiveButton(R.string.btn_Ok, null)
						.setCancelable(false)
			    		.create()
			    		.show();           	
            	
            	result = false;
            }
        } else {
      	
			new AlertDialog.Builder(this)
					.setTitle(R.string.msg_title_no_connection)
					.setMessage(R.string.msg_no_connection)
					.setPositiveButton(R.string.btn_Ok, null)
					.setCancelable(false)
		    		.create()
		    		.show(); 
        	
        	
        	result = false;
        }
        
        return result;
	}//isConnectionAvalable
	
	
	
	/*
	 * Finish activity with result
	 */
	public void finishActivityWithResult(int resultCode){
    	if (getParent() == null) {
    		setResult(resultCode);
		} else {
		    getParent().setResult(resultCode);
		}
    	this.finish();
	}//finishActivityWithResult
	
	
	
	/*
	 * Get tip
	 */
	private static String tip = null;
	
	public void getTip(){
		
//		if(tip != null)
//			return;
		
		TipResponseParser parser = new TipResponseParser(
				Communication.postSOAP(TipService.URL_TIP_SERVICE, TipService.getTip())
			);
		
		tip = parser.getTip();
		if(tip == null)
			tip = "<b>Tip:</b> <a href='http://he-adwords.blogspot.com'>HE AdWords App Tutorial</a>";
		
	}//getTip
	
	
	
	/*
	 * Show tip
	 */
	public void showTip(){
		WebView webView = (WebView) findViewById(R.id.tip_text);
		WebSettings webSettings = webView.getSettings();
		webSettings.setTextSize(WebSettings.TextSize.SMALLER);
		webView.loadData(Converter.escapeURI(tip), "text/html", "utf-8");
	}//showTip
	
	
	
	/*
	 * Strip the list for extension selection
	 */
	public void stripActivity(boolean strip, ListView lv){
		LinearLayout ll_filter = (LinearLayout) findViewById(R.id.ll_filter);
		LinearLayout ll_tips = (LinearLayout) findViewById(R.id.ll_tips);
		LinearLayout ll_totals = (LinearLayout) findViewById(R.id.ll_totals);
		LinearLayout ll_btnFilter = (LinearLayout) findViewById(R.id.ll_btnFilter);
		if(strip){
			
			unregisterForContextMenu(lv);
			ll_filter.setVisibility(View.GONE);
			ll_tips.setVisibility(View.GONE);
			ll_totals.setVisibility(View.GONE);
			ll_btnFilter.setVisibility(View.GONE);
			
		} else {
			
			registerForContextMenu(lv);
			ll_filter.setVisibility(View.VISIBLE);
			ll_tips.setVisibility(View.VISIBLE);
			ll_totals.setVisibility(View.VISIBLE);			
			ll_btnFilter.setVisibility(View.VISIBLE);
			
		}
	}//stripActivity
	
	
//	/*
//	 * Get actual status position for spinner
//	 */
//	public int getStatusPosition(Spinner spinner, int pos){
//		String status = spinner.getItemAtPosition(pos).toString();
//
//		//Set match type spinner position
//		String[] arr_status =  getResources().getStringArray(R.array.arr_status);
//		ArrayList<String> arr_statusList = new ArrayList<String>(Arrays.asList(arr_status));	
//		int position = arr_statusList.indexOf(status);
//
//		return position;
//	}//getStatusPosition
	
}
